var HTTP = (function () {
  let defaultHeaders = {};
  return {
    getRequestParams() {
      const url = window.location;
      const paramsArray = url.search.substring(1).split("&");
      const params = {};
      for (const item of paramsArray) {
        const kv = item.split("=");
        params[kv[0]] = kv[1];
      }
      return params;
    },

    setHeaders(headers) {
      if (!headers) return;
      defaultHeaders = {};
      const keys = Object.keys(headers);
      for (const k of keys) {
        defaultHeaders[k] = headers[k];
      }
    },

    async request(options, wrap = true) {
      const httpRequest = async function () {
        if (!options.url) throw new Error("request url is null");
        let method = "GET";
        let body = undefined;
        let headers = undefined;

        // method
        if (options.method) {
          method = options.method;
        }
        // headers
        if (options.headers || options.header) {
          headers = Object.assign(options.headers || {}, options.header || {});
        } else {
          headers = defaultHeaders;
        }

        // body
        if (
          !options.method ||
          options.method === "GET" ||
          options.method === "get"
        ) {
          body = undefined;
        } else if (
          (headers["Content-Type"] &&
            headers["Content-Type"].includes("form")) ||
          (headers["content-type"] && headers["content-type"].includes("form"))
        ) {
          delete headers["Content-Type"];
          delete headers["content-type"];
          if (options.data instanceof FormData) {
            body = options.data;
          } else if (typeof options.data === "object") {
            body = new FormData();
            const data = options.data || {};
            const keys = Object.keys(data);
            for (const k of keys) {
              body.append(k, data[k]);
            }
          } else {
            throw new Error("wrong data");
          }
        } else if (options.data) {
          body = JSON.stringify(options.data);
          Object.assign(headers, {
            "Content-Type": "application/json;charset=UTF-8",
          });
        }

        let data = undefined;
        if (typeof fetch === "function") {
          data = await fetch(options.url, {
            method,
            headers,
            body,
          }).then((response) => {
            const contentType = response.headers.get("content-type");
            if (contentType && contentType.includes("application/json")) {
              return response.json();
            }
            return response.text();
          });
        } else {
          data = await new Promise((resolve, reject) => {
            const xhr = new XMLHttpRequest();
            xhr.onreadystatechange = () => {
              if (xhr.readyState === XMLHttpRequest.DONE) {
                resolve(xhr.response);
              }
            };
            xhr.onerror = (e) => {
              reject(e);
            };
            xhr.open(method, options.url, true);
            for (const h in headers) {
              xhr.setRequestHeader(h, headers[h]);
            }
            xhr.send(body);
          });
        }
        if (wrap) {
          const response = {
            data,
          };
          return response;
        } else {
          return data;
        }
      };

      // okHTTP3的请求
      // const okHTTP3Request = async function () {
      //   const requestOption = Object.create(options);
      //   try {
      //     if (
      //       !requestOption.url.includes("http://") &&
      //       !requestOption.url.includes("https://")
      //     ) {
      //       requestOption.url =
      //         window.location.protocol +
      //         "//" +
      //         window.location.hostname +
      //         requestOption.url;
      //       // console.log(requestOption.url);
      //     }
      //     if (requestOption.header)
      //       JsBridge.HTTP.setHeaders(requestOption.header);
      //     if (requestOption.headers)
      //       JsBridge.HTTP.setHeaders(requestOption.headers);
      //     if (!requestOption.header && !requestOption.headers)
      //       JsBridge.HTTP.setHeaders(defaultHeaders);

      //     return await new Promise((resolve, reject) => {
      //       requestOption.success = function (result) {
      //         let finalResult = null;
      //         try {
      //           console.log(result);
      //           finalResult = JSON.parse(result);
      //         } catch (e) {
      //           console.error(e);
      //           finalResult = result;
      //         }
      //         if (wrap) {
      //           const response = {
      //             data: finalResult,
      //           };
      //           resolve(response);
      //         } else {
      //           resolve(finalResult);
      //         }
      //       };
      //       requestOption.failed = function (e) {
      //         reject(e);
      //       };

      //       if (
      //         requestOption.data &&
      //         Object.keys(requestOption.data).length === 0
      //       )
      //         requestOption.data = undefined;
      //       if (
      //         !requestOption.method ||
      //         requestOption.method === "GET" ||
      //         requestOption.method === "get"
      //       ) {
      //         JsBridge.HTTP.ajaxForm(requestOption);
      //       } else {
      //         JsBridge.HTTP.ajaxJSON(requestOption);
      //       }
      //     });
      //   } catch (e) {
      //     throw e;
      //   }
      // };

      try {
        // if (JsBridge) return await okHTTP3Request();
        // else return await httpRequest();
        return await httpRequest();
      } catch (e) {
        console.error(e);
        // return await httpRequest();
      }
    },
  };
})();
